package com.dsp18

import android.content.Intent
import android.os.Bundle
import android.net.Uri
import androidx.annotation.NonNull
import android.database.Cursor
import android.provider.OpenableColumns
import java.io.File
import java.io.FileOutputStream
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.dsp18/file"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        // 获取文件 URI 并传递给 Flutter 端
        flutterEngine?.dartExecutor?.binaryMessenger?.let { messenger ->
            MethodChannel(messenger, CHANNEL).apply {
                setMethodCallHandler { call, result ->
                    if (call.method == "getFileUri") {
                        val uri: Uri? = intent?.data
                        if (uri != null) {
                            val filePath = getFilePathFromUri(uri)
                            result.success(filePath)
                        } else {
                            result.success(null)
                        }
                    }
                }
            }
        }
          // 处理首次启动的 Intent
          handleIntent(intent)
    }

      // 处理新的 Intent，当应用已启动并接收到新的 Intent（如文件 URI）
      override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent) // 更新 Intent
        handleIntent(intent)
    }
  
     // 处理 Intent 中的文件 URI
     private fun handleIntent(intent: Intent?) {
        val uri: Uri? = intent?.data
        if (uri != null) {
            val filePath = getFilePathFromUri(uri)
            // 将文件路径通过 MethodChannel 发送到 Flutter
            flutterEngine?.dartExecutor?.binaryMessenger?.let { messenger ->
                MethodChannel(messenger, CHANNEL).invokeMethod("getFileUri", filePath)
            }
        }
    }
    
    ///处理路径，去掉content://，不然flutter不是别家路径
    private fun getFilePathFromUri(uri: Uri): String? {
        val cursor: Cursor? = contentResolver.query(uri, null, null, null, null)
        return if (cursor != null && cursor.moveToFirst()) {
            val displayNameIndex: Int = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            val displayName: String = cursor.getString(displayNameIndex)
    
            // 确保文件路径有效
            val outputFile = File(getExternalFilesDir(null), displayName)
            
            // 从InputStream读取文件内容并写入到outputFile
            contentResolver.openInputStream(uri).use { inputStream ->
                FileOutputStream(outputFile).use { outputStream ->
                    inputStream?.copyTo(outputStream)
                }
            }
    
            cursor.close()
            outputFile.absolutePath
        } else {
            cursor?.close()
            null
        }
    }
    
}
